package com.shipwe.loans.analyse.util

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import androidx.core.content.edit
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.shipwe.loans.analyse.AnalyseBuilder
import com.shipwe.loans.utils.log.ShipweLogger

@SuppressLint("StaticFieldLeak")
object AdvertIdShipweUtil {

    /** sp key gaid */
    private const val SP_KEY_GAID = "GAID"

    /** sp key gaid enable */
    private const val SP_KEY_AD_ENABLE = "ENABLE"

    /** 是否允许广告跟踪 */
    private var _adEnabled: Int = 0

    /** 广告id, 每个接口中的advertId字段 */
    private var _adId: String = ""

    private lateinit var _sp: SharedPreferences
    private lateinit var _context: Context

    /**
     * 初始化
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) { _, _ -> }
    }

    /**
     * 初始化
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String, Int) -> Unit) {
        _context = context
        _sp = context.getSharedPreferences(AnalyseBuilder.product, Context.MODE_PRIVATE).apply {
            if (_adId.isBlank()) {
                _adId = getString(SP_KEY_GAID, "") ?: ""
                _adEnabled = getInt(SP_KEY_AD_ENABLE, 0)
            }
        }

        if (_adId.isBlank()) {
            Thread {
                try {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        val advertisingIdClient = AdvertisingIdClient.getAdvertisingIdInfo(context)
                        val enable = if (advertisingIdClient.isLimitAdTrackingEnabled) 1 else 0
                        _adId = advertisingIdClient.id ?: ""
                        _adEnabled = enable

                        _sp.edit {
                            putInt(SP_KEY_AD_ENABLE, _adEnabled)
                            putString(SP_KEY_GAID, _adId)
                            commit()
                        }
                        ShipweLogger.i("mAdId=$_adId mIsLimitAdTrackingEnabled=$_adEnabled")

                        if (_adId.isNotBlank()) {
                            Handler(Looper.getMainLooper()).post {
                                //回调通知
                                success.invoke(_adId, _adEnabled)
                            }
                        }
                    } else {
                        ShipweLogger.i("init GAID ERROR!!! Cannot call in the main thread, You must call in the other thread")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }.start()
        }
    }

    /**
     * 获取广告id
     *
     * @return 广告id
     */
    fun getAdId(): String {
        return _adId
    }

    /**
     * 获取是否限制广告跟踪
     *
     * @return 限制状态
     */
    fun getAdEnabled(): Int {
        return _adEnabled
    }

    /**
     * 获取安卓id
     *
     * @return 安卓id
     */
    fun getAndroidId(): String {
        val androidID = Settings.System.getString(
            _context.contentResolver,
            Settings.Secure.ANDROID_ID
        )
        if (androidID.isBlank())
            return System.currentTimeMillis().toString()

        if (androidID.contains("00000000"))
            return System.currentTimeMillis().toString()

        return androidID
    }
}